package com.gitee.qdbp.jdbc.stream;

import java.util.List;
import org.springframework.jdbc.core.RowMapper;
import com.gitee.qdbp.jdbc.api.SqlDao;

/**
 * 结果转换后续操作: find() / list()
 *
 * @author zhaohuihua
 * @version 20210530
 */
public class SqlOnResultTypeStream<T> {

    protected final SqlDao dao;
    protected final String sqlId;
    protected final Object params;

    protected final Class<T> resultType;
    protected final RowMapper<T> rowMapper;

    SqlOnResultTypeStream(SqlDao dao, String sqlId, Object params, Class<T> resultType) {
        this.dao = dao;
        this.sqlId = sqlId;
        this.params = params;
        this.resultType = resultType;
        this.rowMapper = null;
    }

    SqlOnResultTypeStream(SqlDao dao, String sqlId, Object params, RowMapper<T> rowMapper) {
        this.dao = dao;
        this.sqlId = sqlId;
        this.params = params;
        this.rowMapper = rowMapper;
        this.resultType = null;
    }

    /**
     * 查询对象<br>
     * <pre>
    SysUser user = qdbcBoot.sqlStream()
        .sqlId("SysUserMapper:findUser")
        .params(map)
        .resultAs(SysUser.class)
        .find();
     * </pre>
     * 
     * @return 查询结果对象
     */
    public T find() {
        if (resultType != null) {
            return this.dao.findForObject(sqlId, params, resultType);
        } else {
            return this.dao.findForObject(sqlId, params, rowMapper);
        }
    }

    /**
     * 查询列表<br>
     * <pre>
    List&lt;SysUser&gt; users = qdbcBoot.sqlStream()
        .sqlId("SysUserMapper:queryRoleUsers")
        .params(map)
        .resultAs(SysUser.class)
        .list();
     * </pre>
     * 
     * @return 查询结果列表
     */
    public List<T> list() {
        if (resultType != null) {
            return this.dao.listForObjects(sqlId, params, resultType);
        } else {
            return this.dao.listForObjects(sqlId, params, rowMapper);
        }
    }
}
